package com.spboot.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.management.relation.RoleResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spboot.entity.Role;
import com.spboot.entity.RolePermission;
import com.spboot.service.PermissionService;
import com.spboot.service.RolePermissionService;
import com.spboot.service.RoleService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author guocb
 * @since 2019-12-25
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	RoleService roleService;

	@Autowired
	PermissionService permissionService;

	@Autowired
	RolePermissionService rolePermissionService;

	@RequestMapping("/list")
	public String list(Model model) {
		model.addAttribute("roleList", roleService.list());
		return "rolelist";
	}

	@RequestMapping("/roleadd")
	public String roleadd(Model model) {

		model.addAttribute("permList", permissionService.list());
		return "roleadd";
	}

	@RequestMapping("/add")
	public String add(Role role, Integer[] permId, Model model) {
		// 添加角色
		boolean f = roleService.save(role);
		if (f) {
			// 添加角色对应的权限
			List<RolePermission> entityList = new ArrayList<>();
			for (Integer perid : permId) {
				entityList.add(new RolePermission(role.getId().intValue(), perid));
			}
			rolePermissionService.saveBatch(entityList);
		} else {

			model.addAttribute("permList", permissionService.list());
			return "roleadd";
		}
		return "redirect:list";
	}

	@RequestMapping("/get")
	public String get(Long id, Model model) {
		model.addAttribute("role", roleService.getById(id));

		model.addAttribute("permList", permissionService.selectPermission(id.intValue()));
		return "roleaedit";
	}

	@RequestMapping("/update")
	public String update(Role role, Integer[] permId, Model model) {
		// 更新角色
		boolean f = roleService.updateById(role);
		if (f) {
			// 清空
			rolePermissionService.remove(new QueryWrapper<RolePermission>().eq(RolePermission.ROLEID, role.getId()));
			// 添加角色对应的权限
			List<RolePermission> entityList = new ArrayList<>();
			for (Integer perid : permId) {
				entityList.add(new RolePermission(role.getId().intValue(), perid));
			}
			rolePermissionService.saveBatch(entityList);
		} else {
			model.addAttribute("role", roleService.getById(role.getId()));
			model.addAttribute("permList", permissionService.selectPermission(role.getId().intValue()));
			return "roleaedit";
		}
		return "redirect:list";
	}
}
